package com.wx.web.interceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.eachonline.core.JsonResult;
import com.eachonline.util.Ip;
import com.eachonline.util.StringUtil;

/**
 * 
 * @ClassName: AuthInterceptor
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author 剑神卓凌昭
 * @date 2015年12月2日 上午12:20:23
 *
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

	private static final Logger LOGGER = Logger
			.getLogger(AuthInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		
		//跨域
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		String uri = request.getServletPath();
		String sessionId="";
		if(null!=request.getParameterMap().get("js_sessionId"))
		 sessionId=request.getParameterMap().get("js_sessionId")[0];
		
		if(StringUtil.isNotEmpty(sessionId))
		{
			AppSessionContext appSessionContext= AppSessionContext.getInstance();  
			 session=appSessionContext.getSession(sessionId);
		}
		
		
		//		Enumeration headerNames = request.getHeaderNames();
//	    while (headerNames.hasMoreElements()) {
//	        String key = (String) headerNames.nextElement();
//	        String value = request.getHeader(key);
//	    	LOGGER.info(key+":---------------"+value);
//	    }

		LOGGER.info("----------begin AuthInterceptor-------------");
		LOGGER.info("User-Agent:---------------"+request.getHeader("User-Agent"));
		LOGGER.info("app version:---------------"+request.getHeader("version"));
		LOGGER.info("ip Address---------------------------------------"+Ip.getIpAddr(request));
		

		LOGGER.info("uri=" + uri);
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				LOGGER.info(cookie.getName() + ":" + cookie.getValue()
						+ ":domain=" + cookie.getDomain() + ":path="
						+ cookie.getPath() + ":toString=" + cookie.toString());
			}
		}

		LOGGER.info("-----------end AuthInterceptor------------");

		
		if (session != null) {
			Object accountObj = session.getAttribute("currentAccount");
			if (accountObj == null) {
				response.setContentType("application/json");
				ServletOutputStream os = response.getOutputStream();

				JsonResult jsonResult = new JsonResult(false, "登录失效");
				jsonResult.setCode("5001");
				String str = JSON.toJSONString(jsonResult);

				IOUtils.write(str, os);
				os.close();
				return false;
			} else {
				return true;
			}
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		super.postHandle(request, response, handler, modelAndView);
	}
}
